import os
import logging
from typing import List, Dict, Any
from transmission_rpc import Client

logger = logging.getLogger(__name__)

class TransmissionClient:
    def __init__(self, host: str, port: int, username: str, password: str):
        self.host = host
        self.port = port
        self.username = username
        self.password = password
        self.client = None

    async def connect(self) -> bool:
        try:
            self.client = Client(
                host=self.host,
                port=self.port,
                username=self.username,
                password=self.password
            )
            return True
        except Exception as e:
            logger.error(f"连接到 Transmission 失败: {str(e)}")
            return False

    async def get_torrents(self) -> List[Dict]:
        try:
            result = []
            for torrent in self.client.get_torrents():
                try:
                    files = []
                    if hasattr(torrent, 'files') and callable(torrent.files):
                        try:
                            for file_id, file_info in torrent.files().items():
                                file_name = file_info.get('name', '')
                                if file_name:
                                    files.append(file_name)
                        except Exception as file_err:
                            logger.warning(f"获取种子文件列表时出错: {str(file_err)}")
                    
                    result.append({
                        "hash": getattr(torrent, 'hashString', ''),
                        "name": getattr(torrent, 'name', '未知'),
                        "files": files,
                        "save_path": getattr(torrent, 'download_dir', ''),
                        "status": str(getattr(torrent, 'status', '')),
                        "percent_done": getattr(torrent, 'percent_done', 0)
                    })
                except Exception as torrent_err:
                    logger.warning(f"处理单个种子信息时出错: {str(torrent_err)}")
            
            logger.info(f"从Transmission获取到 {len(result)} 个种子")
            return result
        except Exception as e:
            logger.error(f"获取种子信息失败: {str(e)}")
            return []
    
    async def get_seeding_files(self) -> List[Dict[str, Any]]:
        """获取正在做种的文件列表"""
        try:
            if not self.client:
                if not await self.connect():
                    raise Exception("无法连接到 Transmission")

            torrents = self.client.get_torrents()
            seeding_files = []
            
            # 记录种子状态分布情况，用于调试
            status_counts = {}
            
            logger.info(f"获取到 {len(torrents)} 个种子")
            
            for torrent in torrents:
                # 记录每种状态的数量
                status = str(torrent.status)
                status_counts[status] = status_counts.get(status, 0) + 1
                
                # 处理所有已完成的种子（不仅仅是'seeding'状态）
                # Transmission可能使用不同的状态值表示做种

                if torrent.percent_done == 100 or status.lower() in ['seeding', 'seed', 'seed_wait', 'finished', 'done', 'complete', 'completed']:
                    base_path = torrent.download_dir
                    # logger.info(f"处理种子: {torrent.name}, 状态: {status}, 下载目录: {base_path}")
                    
                    # 获取种子中的所有文件 - 使用get_files()方法而不是files()
                    try:
                        torrent_files = torrent.get_files()
                        # logger.info(f"种子 {torrent.name} 包含 {len(torrent_files)} 个文件")
                        
                        for file in torrent_files:
                            file_name = file.name
                            file_size = file.size
                            
                            if file_name:
                                # 构建完整文件路径
                                file_path = os.path.join(base_path, file_name)
                                # logger.info(f"检查文件: {file_path}")
                                
                                if os.path.exists(file_path):  # 只添加实际存在的文件
                                    seeding_files.append({
                                        "path": file_path,
                                        "name": os.path.basename(file_path),
                                        "size": file_size
                                    })
                                    # logger.info(f"添加做种文件: {file_path}")
                                else:
                                    pass
                                    # logger.warning(f"文件不存在: {file_path}")
                    except Exception as file_err:
                        logger.warning(f"处理种子文件时出错: {str(file_err)}")
            
            # 记录状态分布情况
            logger.info(f"Transmission种子状态分布: {status_counts}")
            logger.info(f"从 Transmission 获取到 {len(seeding_files)} 个本地文件实际存在的做种文件")
            return seeding_files
            
        except Exception as e:
            logger.error(f"获取 Transmission 做种文件失败: {str(e)}")
            raise
    
    async def test_connection(self) -> bool:
        try:
            logger.info(f"尝试连接Transmission: {self.host}:{self.port}, 用户名: {self.username}")
            self.client = Client(
                host=self.host,  # 使用host而不是address
                port=self.port,
                username=self.username,  # 使用username而不是user
                password=self.password
            )
            logger.info("Transmission客户端创建成功，尝试获取会话统计信息")
            self.client.session_stats()
            logger.info("Transmission连接测试成功")
            return True
        except Exception as e:
            logger.error(f"Transmission连接测试失败: {str(e)}")
            return False
